import { Link, useNavigate } from "react-router-dom";
import { Card, Breadcrumb, Form, DatePicker, Select } from "antd";
import PopConfirm from "@/components/PopConfirm";

// 时间选择器汉化包
import locale from "antd/es/date-picker/locale/zh_CN";

// 导入资源
import { Table, Tag, Space } from "antd";
import img404 from "@/assets/error.png";
import { useChannel } from "@/hooks/useChannel";
import { useEffect, useState } from "react";
import { deleteArticleAPI, getArticleListAPI } from "@/apis/article";

const { Option } = Select;
const { RangePicker } = DatePicker;

const Article = () => {
  const navigate = useNavigate();
  // 删除
  const onConfirm = (data) => {
    console.log("删除成功", data);
    deleteArticleAPI(data.id).then(() => {
      setReqData({
        ...reqData,
      });
    });
  };

  // 分页
  const onPageChange = (page) => {
    console.log(page);
    setReqData({
      ...reqData,
      page: page,
    });
  };

  // 定义枚举状态
  const status = {
    1: <Tag color="warning">待审核</Tag>,
    2: <Tag color="success">审核通过</Tag>,
  };

  // 单选按钮
  const [radio, setRadio] = useState("");
  const onTypeChange = (e) => {
    console.log(e.target.value);
    setRadio(e.target.value);
  };

  // 准备列数据
  const columns = [
    {
      title: "封面",
      dataIndex: "cover",
      width: 120,
      render: (cover) => {
        return (
          <img src={cover.images[0] || img404} width={80} height={60} alt="" />
        );
      },
    },
    {
      title: "标题",
      dataIndex: "title",
      width: 220,
    },
    {
      title: "状态",
      dataIndex: "status",
      render: (data) => status[data],
    },
    {
      title: "发布时间",
      dataIndex: "pubdate",
    },
    {
      title: "阅读数",
      dataIndex: "read_count",
    },
    {
      title: "评论数",
      dataIndex: "comment_count",
    },
    {
      title: "点赞数",
      dataIndex: "like_count",
    },
    {
      title: "操作",
      render: (data) => {
        return (
          <Space size="middle">
            <button
              style={{
                backgroundColor: "#1890ff",
                color: "#fff",
                border: "none",
                padding: "5px 10px",
                borderRadius: "5px",
              }}
              onClick={() => {
                navigate(`/publish?id=${data.id}`);
              }}
            >
              编辑
            </button>
            <PopConfirm
              title="确认删除吗？"
              onConfirm={() => {
                onConfirm(data);
              }}
              onCancel={() => {
                console.log("取消");
              }}
            >
              <button
                style={{
                  backgroundColor: "#f5222d",
                  color: "#fff",
                  border: "none",
                  padding: "5px 10px",
                  borderRadius: "5px",
                }}
              >
                删除
              </button>
            </PopConfirm>
          </Space>
        );
      },
    },
  ];
  // 筛选功能
  const [reqData, setReqData] = useState({
    status: "",
    channel_id: "",
    begin_pubdate: "",
    end_pubdate: "",
    page: 1,
    per_page: 8,
  });
  // 获取文章列表
  const [list, setList] = useState([]);
  const [count, setCount] = useState(0);
  useEffect(() => {
    const getList = async () => {
      const res = await getArticleListAPI(reqData);
      setList(res.data.results);
      setCount(res.data.total_count);
    };
    getList();
  }, [reqData]);

  // 获取频道
  const { channelList } = useChannel();

  // 准备请求参数
  const onFinish = (values) => {
    values.status = radio;
    console.log(values);
    setReqData({
      ...reqData,
      status: values.status,
      channel_id: values.channel_id,
      begin_pubdate: values.date[0].format("YYYY-MM-DD"),
      end_pubdate: values.date[1].format("YYYY-MM-DD"),
    });
  };
  return (
    <div>
      <Card
        title={
          <Breadcrumb
            items={[
              { title: <Link to={"/"}>首页</Link> },
              { title: "文章列表" },
            ]}
          />
        }
        style={{ marginBottom: 20 }}
      >
        <Form initialValues={{ status: "" }} onFinish={onFinish}>
          <Form.Item label="状态" name="status">
            <input
              type="radio"
              id="single"
              name="imageOption"
              value={""}
              onChange={onTypeChange}
              checked={radio === ""}
            />
            <label htmlFor="single">全部</label>

            <input
              type="radio"
              id="triple"
              name="imageOption"
              value={0}
              onChange={onTypeChange}
              checked={radio === "0"}
            />
            <label htmlFor="triple">草稿</label>

            <input
              type="radio"
              id="none"
              name="imageOption"
              value={2}
              onChange={onTypeChange}
              checked={radio === "2"}
            />
            <label htmlFor="none">审核通过</label>
          </Form.Item>

          <Form.Item label="频道" name="channel_id">
            <Select
              placeholder="请选择文章频道"
              defaultValue="lucy"
              style={{ width: 120 }}
            >
              {channelList.map((item) => {
                return (
                  <Option key={item.id} value={item.id}>
                    {item.name}
                  </Option>
                );
              })}
            </Select>
          </Form.Item>

          <Form.Item label="日期" name="date">
            {/* 传入locale属性 控制中文显示*/}
            <RangePicker locale={locale}></RangePicker>
          </Form.Item>

          <Form.Item>
            <button>筛选</button>
          </Form.Item>
        </Form>
      </Card>

      {/*   表格区域   */}
      <Card title={`根据筛选条件共查询到 ${count} 条结果：`}>
        <Table
          rowKey="id"
          columns={columns}
          dataSource={list}
          pagination={{
            pageSize: reqData.per_page, // 每页显示的条数
            total: count, // 数据总数
            onChange: onPageChange,
          }}
        />
      </Card>
    </div>
  );
};

export default Article;
